from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from apps.articles.models import Article, Category, ArticleImages, ArticleContent
from apps.users.models import User
from utils.constants import QINIU_DOMAIN
from utils.models import BaseModelSerializer


class CategoryModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')


class ArticleContentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleContent
        fields = ('content',)


class ArticleImagesModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleImages
        fields = ('url',)


class ArticleUserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'decorate_avatar', 'mobile', 'sex', 'fans']


class ArticleModelSerializer(BaseModelSerializer):
    author = ArticleUserModelSerializer(read_only=True)
    author_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    category = serializers.StringRelatedField()
    content = ArticleContentModelSerializer(write_only=True)
    images = ArticleImagesModelSerializer(many=True, write_only=True)
    comment_count = serializers.IntegerField()

    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ('collection_users', 'category', 'ctime', 'comment_count')

    def validate_content(self, value):
        try:
            if not len(value.get('content')) > 0:
                raise serializers.ValidationError('The length of this field must be greater than 0.')
            return value
        except Exception:
            raise serializers.ValidationError('The length of this field must be greater than 0.')

    def create(self, validated_data):
        content_dict = validated_data.pop('content')
        images_list = validated_data.pop('images')
        article = Article.objects.create(**validated_data)
        content_data = content_dict.get('content')
        ArticleContent.objects.create(content=content_data, article=article)
        for image in images_list:
            ArticleImages.objects.create(url=image['url'].replace(QINIU_DOMAIN, ''), article=article)
        return article


class ESArticleModelSerializer(ModelSerializer):
    author_id = serializers.IntegerField()
    category = serializers.StringRelatedField()
    content = serializers.StringRelatedField()

    class Meta:
        model = Article
        fields = ['id', 'author_id', 'title', 'content', 'create_time', 'category']
